<template>
	<u-upload
		:disabled="disabled"
		:file-list="fileList"
		v-bind="$attrs"
		@afterRead="handleUploadAfterRead"
		@delete="handleDelete"
	/>
</template>

<script>
	import { useUserStore } from "@/store/user";
	import config from "@/common/config.js";
	import { ref, watch } from "vue";

	const userStore = useUserStore();

	export default {
		props: {
			modelValue: {
				type: Array,
				default: () => [],
			},
			disabled: {
				type: Boolean,
				default: false,
			},
		},

		emits: ["update:modelValue", "upload", "delete"],

		setup(props, { emit }) {
			const fileList = ref(props.modelValue);

			watch(
				() => props.modelValue,
				(val) => {
					fileList.value = props.modelValue;
				},
			);

			async function handleUploadAfterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = fileList.value.length;
				lists.map((item) => {
					fileList.value.push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await uploadFilePromise(lists[i].url);
					let item = fileList.value[fileListLen];
					fileList.value.splice(fileListLen, 1, {
						...item,
						status: "success",
						message: "",
						url: result,
					});
					fileListLen++;
				}
			}

			function uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.baseUploadUrl,
						filePath: url,
						name: "file",
						header: {
							Authorization: `Bearer ${userStore.token}`,
						},
						success: (res) => {
							const response = JSON.parse(res.data);
							if (response.success) {
								resolve(response.data.url);
								emit("upload", response.data.url);
							} else {
								reject(response);
							}
						},
					});
				});
			}

			function handleDelete(e) {
				fileList.value.splice(e.index, 1);
				emit("delete", e);
			}

			return {
				fileList,
				handleUploadAfterRead,
				uploadFilePromise,
				handleDelete,
			};
		},
	};
</script>

<style lang="scss" scoped></style>
